package com.lzy.webapi.facade;

import com.lzy.base.apis.SysUserAdminServiceApi;
import com.lzy.base.dtos.SysUserAdminDto;
import com.lzy.base.dtos.SysUserIdentityDto;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.tools.commons.PropertiesUtils;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.member.dtos.MemberUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * 后台用户信息
 */
@Component
public class SysUserAdminServiceFacade {

    @Autowired
    private MemberUserServiceApi memberUserServiceApi;

    @Autowired
    private SysUserAdminServiceApi sysUserAdminServiceApi;

    /**
     * 根据会员id新增后台用户
     * @param sysUserAdminDto
     * @param sysUserIdentity
     * @param flag
     * @return
     */
    public Long insert(SysUserAdminDto sysUserAdminDto, SysUserIdentityDto sysUserIdentity, String flag){
        Ensure.that(sysUserAdminDto).isNotNull("00000004");
        Ensure.that(sysUserAdminDto.getPhone()).isNotNull("00000015");
        //获取到会员的id
        Long memberId = 0L;
        MemberUserDto memberUserDto = memberUserServiceApi.findMemberByMobile(sysUserAdminDto.getPhone());
        if (memberUserDto == null){//会员信息不存在，需要新增
            memberUserDto = new MemberUserDto();
            memberUserDto.setName(sysUserAdminDto.getRealName());
            memberUserDto.setAccount(sysUserAdminDto.getPhone());
            memberUserDto.setIDNumber(sysUserAdminDto.getIDNumber());
            Properties props = PropertiesUtils.load("props/config.properties");
            if (sysUserAdminDto.getMemberPassword()==null || "".equals(sysUserAdminDto.getMemberPassword()))
                sysUserAdminDto.setMemberPassword(props.getProperty("default.password"));
            memberUserDto.setPassWord(sysUserAdminDto.getMemberPassword());
            MemberUserDto memberDto = memberUserServiceApi.addMember(memberUserDto);
            memberId = memberDto.getId();
        } else {//会员信息已经存在
            memberId = memberUserDto.getId();
        }
        //新增后台用户，id使用会员的id，保持一致
        SysUserAdminDto dto = sysUserAdminServiceApi.selectByPhone(sysUserAdminDto.getPhone());
        if (dto != null){
            return dto.getId();
        }
        sysUserAdminDto.setId(memberId);
        Long userId = sysUserAdminServiceApi.insert(sysUserAdminDto, sysUserIdentity, "1");
        return userId;
    }

    public SysUserAdminDto selectByPhone(String phone){
       return sysUserAdminServiceApi.selectByPhone(phone);
    }
}
